package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryList() {
        String key = "shop_type:";
        //1.redis中查询
        String shopTypeJSON = stringRedisTemplate.opsForValue().get(key);
        //2.存在，返回数据
        if (StrUtil.isNotBlank(shopTypeJSON)) {
            return JSONUtil.toList(shopTypeJSON, ShopType.class);
        }
        //3.不存在，数据库中查询，写入redis并返回
        List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();
        if(shopTypeList.isEmpty()){
            return new ArrayList<ShopType>();
        }
        //4.数据库中的数据写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList),SHOP_TYPE_TTL, TimeUnit.MINUTES);
        return shopTypeList;
    }
}
